package com.lyb.spzx.manager.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.ListUtils;
import com.lyb.spzx.manager.mapper.CategoryMapper;
import com.lyb.spzx.model.vo.product.CategoryExcelVo;

import java.util.List;

public class ExcelListener<T> extends AnalysisEventListener<T> {

    private static final int BATCH_COUNT = 100;

    //缓存的数据
    List categoryList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    //获取mapper对象
    private CategoryMapper categoryMapper;

    public ExcelListener() {
    }

    public ExcelListener(CategoryMapper categoryMapper) {
        this.categoryMapper = categoryMapper;
    }


    @Override
    public void invoke(T t, AnalysisContext analysisContext) {

        CategoryExcelVo categoryExcelVo = (CategoryExcelVo) t;
        categoryList.add(categoryExcelVo);
        //达到BATCH_COUNT条数后，需要去存储一次数据库，防止数据过多，导致OOM
        if (categoryList.size() >= BATCH_COUNT){
            saveDatabase();
            //保存完，清理list
            categoryList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    private void saveDatabase() {
        categoryMapper.batchInsert(categoryList);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveDatabase();
    }
}
